package com.jeesite.modules.formcategory.web;

import java.util.Map;
import java.util.List;

import com.jeesite.common.utils.OrgUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.formcategory.entity.FormCategory;
import com.jeesite.modules.formcategory.service.FormCategoryService;

/**
 * 表单类别Controller
 * @author 码脑洞
 * @version 2025-04-13
 */
@Controller
@RequestMapping(value = "${adminPath}/formcategory/formCategory")
public class FormCategoryController extends BaseController {

	@Autowired
	private FormCategoryService formCategoryService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public FormCategory get(Long autoId, boolean isNewRecord) {
		return formCategoryService.get(autoId, isNewRecord);
	}

	/**
	 * 管理主页
	 */
	@RequiresPermissions("formcategory:formCategory:view")
	@RequestMapping(value = "index")
	public String index(FormCategory formCategory, Model model) {
		model.addAttribute("formCategory", formCategory);
		return "modules/formcategory/formCategoryIndex";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("formcategory:formCategory:view")
	@RequestMapping(value = {"list", ""})
	public String list(FormCategory formCategory, Model model) {
		model.addAttribute("formCategory", formCategory);
		return "modules/formcategory/formCategoryList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("formcategory:formCategory:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<FormCategory> listData(FormCategory formCategory) {
		if (StringUtils.isBlank(formCategory.getParentCode())) {
			formCategory.setParentCode(FormCategory.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(formCategory.getCode())){
			formCategory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(formCategory.getName())){
			formCategory.setParentCode(null);
		}
		List<FormCategory> list = formCategoryService.findList(formCategory);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("formcategory:formCategory:view")
	@RequestMapping(value = "form")
	public String form(FormCategory formCategory, Model model) {
		if (OrgUtil.isValid()){
			formCategory.setOrgId(OrgUtil.getOrgId());
			formCategory.setOrgCode(OrgUtil.getOrgCode());
			formCategory.setOrgName(OrgUtil.getOrgName());
		}
		// 创建并初始化下一个节点信息
		formCategory = createNextNode(formCategory);
		model.addAttribute("formCategory", formCategory);
		return "modules/formcategory/formCategoryForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("formcategory:formCategory:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public FormCategory createNextNode(FormCategory formCategory) {
		if (StringUtils.isNotBlank(formCategory.getParentCode())){
			formCategory.setParent(formCategoryService.get(formCategory.getParentCode()));
		}
		if (formCategory.getIsNewRecord()) {
			FormCategory where = new FormCategory();
			where.setParentCode(formCategory.getParentCode());
			FormCategory last = formCategoryService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				formCategory.setTreeSort(last.getTreeSort() + 30);
			}
		}
		// 以下设置表单默认数据
		if (formCategory.getTreeSort() == null){
			formCategory.setTreeSort(FormCategory.DEFAULT_TREE_SORT);
		}
		return formCategory;
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("formcategory:formCategory:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated FormCategory formCategory) {
		formCategoryService.save(formCategory);
		return renderResult(Global.TRUE, text("保存表单类别成功！"));
	}
	
	/**
	 * 验证类别编码是否唯一
	 */
	@ResponseBody
	@RequestMapping(value = "checkCodeUnique")
	public Boolean checkCodeUnique(String code, String oldCode) {
		FormCategory formCategory = new FormCategory();
		formCategory.setCode(code);
		formCategory.setOrgId(OrgUtil.getOrgId());
		if (code != null && code.equals(oldCode)) {
			return true;
		} else {
			return formCategoryService.checkCodeUnique(formCategory) == null;
		}
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("formcategory:formCategory:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(FormCategory formCategory) {
		FormCategory where = new FormCategory();
		where.setStatus(FormCategory.STATUS_NORMAL);
		where.setParentCodes("," + formCategory.getId() + ",");
		long count = formCategoryService.findCount(where);
		if (count > 0) {
			return renderResult(Global.FALSE, text("该表单类别包含未停用的子表单类别！"));
		}
		formCategory.setStatus(FormCategory.STATUS_DISABLE);
		formCategoryService.updateStatus(formCategory);
		return renderResult(Global.TRUE, text("停用表单类别成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("formcategory:formCategory:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(FormCategory formCategory) {
		formCategory.setStatus(FormCategory.STATUS_NORMAL);
		formCategoryService.updateStatus(formCategory);
		return renderResult(Global.TRUE, text("启用表单类别成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("formcategory:formCategory:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(FormCategory formCategory) {
		formCategoryService.delete(formCategory);
		return renderResult(Global.TRUE, text("删除表单类别成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param parentCode 设置父级编码返回一级
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("formcategory:formCategory:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String parentCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		FormCategory where = new FormCategory();
		where.setStatus(FormCategory.STATUS_NORMAL);
		if (StringUtils.isNotBlank(parentCode)){
			where.setParentCode(parentCode);
		}
		List<FormCategory> list = formCategoryService.findList(where);
		for (int i=0; i<list.size(); i++){
			FormCategory e = list.get(i);
			// 过滤非正常的数据
			if (!FormCategory.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", e.getName());
			map.put("isParent", !e.getIsTreeLeaf());
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("formcategory:formCategory:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(FormCategory formCategory){
		if (!formCategory.currentUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		formCategoryService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}
	
}